<template>
  <el-card>
    <el-table
      :data="category1List"
      style="width: 100%"
      :row-key="getRowKey"
      border
      v-loading="loading"
      lazy
      :load="load"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="id" label="分类ID"></el-table-column>
      <el-table-column prop="name" label="分类名称"></el-table-column>
      <el-table-column label="操作">
        <template #header>
          <el-input placeholder="按enter键添加一级分类"></el-input>
        </template>
        <template v-slot="">
          <el-button type="primary" size="small" :icon="Plus"></el-button>
          <el-button type="primary" size="small" :icon="Edit"></el-button>
          <el-button type="danger" size="small" :icon="Delete"></el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>

<script lang="ts">
export default {
  name: 'Category',
}
</script>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { Delete, Edit, Plus, Message, Search } from '@element-plus/icons-vue'
import {
  reqGetCategory1ListData,
  reqGetCategory2ListData,
  reqGetCategory3ListData,
} from '@/api/product/category'
import type {
  CategoryListModel,
  CategoryModel,
} from '@/api/product/model/categoryModel'
import { ElMessage } from 'element-plus'

const loading = ref(false)
const category1List = ref<CategoryListModel>([])

const getCategory1ListData = async () => {
  loading.value = true
  const result = await reqGetCategory1ListData()
  category1List.value = result
  category1List.value.forEach((category1) => {
    // 用于显示展开按钮
    category1.hasChildren = true
    // 用于说明当前分类对象的等级
    category1.level = 1
  })
  loading.value = false
}

// 用于给每一行添加一个唯一的row-key值，防止出现死递归
const getRowKey = (row: CategoryModel) => {
  return `${row.level}-${row.id}`
}

// 当用户第一次点击没有展开的分类的时候，会执行该函数
const load = async (
  row: CategoryModel,
  treeNode: unknown,
  resolve: (data: CategoryModel[]) => void
) => {
  // 如果已经获取到了数据，可以通过resolve方法将数据传递给当前的table表格实现树形展
  if (row.level === 1) {
    // 说明要展开二级列表
    const category2List = await reqGetCategory2ListData(row.id)
    ElMessage.success('二级分类数据获取成功...')

    category2List.forEach((category2) => {
      // {id:10,name:''}
      category2.hasChildren = true
      // 当前自己的分类项
      category2.level = 2

      // 将请求回来的数据交给table表格 当单击箭头的时候，会进行一个二级列表的展示
      resolve(category2List)
    })
  } else if (row.level === 2) {
    // 如果level是2的话，说明此时去获取三级数
    const category3List = await reqGetCategory3ListData(row.id)
    category3List.forEach((category3) => {
      // 已经没有子项了
      category3.hasChildren = false
      // 设置一个三级level
      category3.level = 3

      // 交给el-table来处理三级分类
      resolve(category3List)
    })
  }
}

onMounted(() => {
  getCategory1ListData()
})
</script>
<style></style>
